﻿using MuXue.Zyiz.Template.Domain.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MuXue.Zyiz.Template.WebApi.Filter
{
    public class GlobalExceptions : IExceptionFilter
    {
        private ILogger _logger;
        public GlobalExceptions(ILogger<GlobalExceptions> logger)
        {
            _logger = logger;
        }
        public void OnException(ExceptionContext context)
        {
            Exception exception = context.Exception;
            var controller = context.RouteData.Values["controller"].ToString();
            var action = context.RouteData.Values["Action"].ToString();
            var errorPath = controller + "/" + action;
            _logger.LogError(exception,"web service error:" + errorPath,  exception.Message);
            var statusCode = context.HttpContext.Response.StatusCode;
            context.Result = new JsonResult(new Result<string>() { state = false, error_code = statusCode.ToString(), error_msg = string.Concat("错误路径", errorPath, "错误信息", exception.Message) });
        }
    }
}
